package cn.ichiva.puppet.example.curd;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class DepartmentDao implements Dao<Department,Long>{

    ConcurrentHashMap<Long, Department> deptMap = new ConcurrentHashMap<>(){
        {
            Department department = new Department();
            department.setId(1L);
            department.setName("总裁办");
            department.setMarket("马云,刘强东...");
            put(department.getId(),department);

            Department it = new Department();
            it.setId(11L);
            it.setName("技术部");
            it.setMarket("张泽天...");
            it.setSuperDept(1L);
            put(it.getId(),it);
        }
    };

    @Override
    public void add(Department entity) {
        if(entity.getId() == null){
            Long id = System.currentTimeMillis();
            entity.setId(id);
        }else {
            if (deptMap.containsKey(entity.getId())) {
                throw new RuntimeException("主键ID冲突");
            }
        }

        deptMap.put(entity.getId(), entity);
    }

    @Override
    public void del(Long id) {
        deptMap.remove(id);
    }

    @Override
    public void update(Department entity) {
        if(entity.getId() == null){
            throw new RuntimeException("主键ID不能为空");
        }

        if(deptMap.containsKey(entity.getId())){
            throw new RuntimeException("主键ID不存在");
        }

        deptMap.put(entity.getId(), entity);
    }

    @Override
    public List<Department> find(Department entity) {
        List<Department> res = findAll();
        if(entity.getId() != null){
            res = res.stream().filter(e -> entity.getId().equals(e.getId())).collect(Collectors.toList());
        }

        if(entity.getName() != null){
            res = res.stream().filter(e -> entity.getName().equals(e.getName())).collect(Collectors.toList());
        }

        if(entity.getSuperDept() != null){
            res = res.stream().filter(e -> entity.getSuperDept().equals(e.getSuperDept())).collect(Collectors.toList());
        }

        if(entity.getMarket() != null){
            res = res.stream().filter(e -> entity.getMarket().equals(e.getMarket())).collect(Collectors.toList());
        }

        return res;
    }

    @Override
    public List<Department> findAll() {
        return new ArrayList<>(deptMap.values());
    }
}
